package com.cyh.ClassLoaderStudy;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

/**
 * Created by yanhuche on 5/18/2017.
 */
public class DifferentClassLoaderLoadTheSameClass {


    public static void main(String[] args) throws Exception {

        ClassLoader myLoader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                try {
                    String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
                    InputStream is = getClass().getResourceAsStream(fileName);
                    if (is == null) {
                        System.err.println("is == null");
                        return super.loadClass(name);
                    }
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    return defineClass(name, b, 0, b.length);
                } catch (IOException e) {
                    throw new ClassNotFoundException(name);
                }
            }
        };

        TimeUnit.SECONDS.sleep(5);
        Class<?> aClass = myLoader.loadClass("com.cyh.ClassLoaderStudy.DifferentClassLoaderLoadTheSameClass");
        TimeUnit.SECONDS.sleep(5);
        Object obj = aClass.newInstance();
        TimeUnit.SECONDS.sleep(5);

        System.out.println(obj.getClass());
        System.out.println(obj instanceof com.cyh.ClassLoaderStudy.DifferentClassLoaderLoadTheSameClass);
    }
}
